package com.ea.common.handler;

import com.ea.common.result.BizException;
import com.ea.common.result.ErrorCode;
import com.ea.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.List;

/**
 * 对加了@RestController注解方法的进行拦截处理，实际上是AOP环绕实现
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 定义@Valid注解全局异常处理机制
     */
    @ExceptionHandler(BindException.class)
    public Result validationBodyException(BindException e) {
        // 打印校验住的所有的错误信息
        StringBuilder sb = new StringBuilder("参数错误：[");
        List<ObjectError> list = e.getAllErrors();
        for (ObjectError item : list) {
            sb.append(item.getDefaultMessage()).append(',');
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(']');
        String msg = sb.toString();
        return Result.fail(
                ErrorCode.USER_PARAM_ERROR_NULL_PARAM.getCode(),
                msg
        );
    }

    /**
     * 业务异常处理器
     *
     * @param bizException 业务异常对象
     */
    @ExceptionHandler(BizException.class)
    public Result handleBizException(BizException bizException) {
        if (bizException.getErrorCode() == ErrorCode.SYSTEM_RESOURCE_ERROR_REPORT_NOT_EXISTS) {
            return Result.fail(ErrorCode.SYSTEM_ERROR.getCode(), bizException.getMessage());
        }if(bizException.getErrorCode()==ErrorCode.TPS_FILE_UPLOAD_FACE_NO_CORRECT_ERROR){
            return Result.fail(ErrorCode.TPS_FILE_UPLOAD_FACE_NO_CORRECT_ERROR.getCode(),bizException.getMessage());
        }
         if(bizException.getErrorCode()==ErrorCode.TPS_FILE_UPLOAD_FACE_EXIST_ERROR){
             return Result.fail(ErrorCode.TPS_FILE_UPLOAD_FACE_EXIST_ERROR.getCode(),bizException.getMessage());
         }
        log.error("业务Exception: {}", bizException.getMessage());
        log.error("stack: {}", Arrays.toString(bizException.getStackTrace()));

        return Result.fail(bizException.getErrorCode().getCode(), bizException.getErrorCode().getMsg());
    }

    /**
     * 异常处理器
     * @param exception 其他异常对象
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception exception) {
        log.error("Exception: {}", exception.getMessage());
        log.error("stack: {}", Arrays.toString(exception.getStackTrace()));

        return Result.fail(ErrorCode.SYSTEM_ERROR.getCode(), exception.getMessage());
    }
}
